package com.atguigu.springboot.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 19shusheng.com
 * @Description:
 * @Date: Created in 21:40 2020/10/29
 * @Modified By:
 */
@Component
public class MyLB implements LoadBalancer {
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     *
     * @Description:
     * 此处实现的是cas+自旋
     * @auther: madonghui
     * @date: 21:52 2020/10/29
     * @param: []
     * @return: int
     *
     */
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            /**
             *
             * @Description: 判断是否大于等于int的最大值，有可能访问次数会增加到临界值
             *
             * @auther: madonghui
             * @date: 21:58 2020/10/29
             * @param: []
             * @return: int
             *
             */
            next = current >= 2147483647 ? 0 : current + 1;
            /**
             *
             * @Description: 此处是cas+自旋  第一个参数是期望值，第二个参数是要修改的值
             *
             * @auther: madonghui
             * @date: 21:59 2020/10/29
             * @param: []
             * @return: int
             *
             */
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println(".........第几次访问数：next="+next);
        return next;
    }
    /**
     *
     * @Description:
     *   获取到机器的列表
     * @auther: madonghui
     * @date: 21:42 2020/10/29
     * @param: [serviceInstances]
     * @return: org.springframework.cloud.client.ServiceInstance
     *
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        /**
         *
         * @Description: 获取机器下标
         *
         * @auther: madonghui
         * @date: 22:03 2020/10/29
         * @param: [serviceInstances]
         * @return: org.springframework.cloud.client.ServiceInstance
         *
         */
        int index = getAndIncrement() % serviceInstances.size();
        return null;
    }
}
